package com.zy.factory;

import lombok.Data;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

// 自定义权限断言工厂
//@Component
public class AuthRoutePredicateFactory extends AbstractRoutePredicateFactory<AuthRoutePredicateFactory.Config> {

    // 指定读取属性顺序
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("userName", "password");
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return serverWebExchange -> {
            // 获取请求头中的所有header
            HttpHeaders headers = serverWebExchange.getRequest().getHeaders();
            // 一个请求头可以包含多个值
            List<String> passwords = headers.get(config.getUserName());
            // 如果包含则放行
            return passwords.contains(config.getPassword());
        };
    }

    public AuthRoutePredicateFactory() {
        super(Config.class);
    }

    @Data
    public static class Config {
        private String userName;
        private String password;
    }
}
